package com.qcrud.jte;

import com.qcrud.core.SqlData;
import com.qcrud.core.SqlManager;
import com.qcrud.core.SqlMeta;
import com.qcrud.core.SqlTemplate;
import com.qcrud.core.type.DataType;
import com.qcrud.tookit.ConstantPool;
import gg.jte.ContentType;
import gg.jte.TemplateEngine;
import gg.jte.output.StringOutput;

import java.util.List;
import java.util.Map;

public class JteSqlTemplate implements SqlTemplate {
    final DummyCodeResolver dummyCodeResolver = new DummyCodeResolver();
    final TemplateEngine templateEngine = TemplateEngine.create(dummyCodeResolver, ContentType.Plain);

    @Override
    public void render(SqlData sqlData) {
        final String templateName = sqlData.getStatementKey();
        final SqlMeta sqlMeta = sqlData.getSqlMeta();
        final Map<String, Object> params = sqlData.getParams();
        dummyCodeResolver.givenCode(templateName, () -> {
            // 导入参数处理
            StringBuffer ic = new StringBuffer();
            StringBuffer pc = new StringBuffer();
            ic.append("@import com.qcrud.core.sql.CrudSql\n");
            pc.append("@param CrudSql sql\n");
            params.forEach((k, v) -> {
                if (!k.startsWith(ConstantPool.QCRUD)) {
                    Class cls = v.getClass();
                    DataType dataType = DataType.of(cls);
                    if (null != dataType) {
                        pc.append("@param ").append(dataType.name());
                    } else if (List.class.isAssignableFrom(cls)) {
                        ic.append("@import ").append(List.class.getName()).append("\n");
                        pc.append("@param List<Object>");
                    } else {
                        ic.append("@import ").append(cls.getName()).append("\n");
                        pc.append("@param ").append(cls.getSimpleName());
                    }
                    pc.append(" ").append(k).append("\n");
                }
            });
            // 原始 SQL 内容
            pc.append("\n").append(sqlMeta.getRawSql());
            return ic.append("\n").append(pc).toString();
        });
        // 注入 SQL 操作类
        params.put("sql", SqlManager.initCrudSql(sqlData));
        StringOutput output = new StringOutput();
        templateEngine.render(templateName, params, output);
        sqlData.setSql(output.toString());
    }
}
